package com.css.fxfzfxqh.modules.buildings.calculationTasks.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzfxqh.base.dict.service.DictItemService;
import com.css.fxfzfxqh.base.dict.viewobjects.DictEntityVo;
import com.css.fxfzfxqh.base.response.RestResponse;
import com.css.fxfzfxqh.common.rest.JcsjRestManager;
import com.css.fxfzfxqh.constants.FxfzConstants;
import com.css.fxfzfxqh.constants.YNEnum;
import com.css.fxfzfxqh.modules.buildingIndividual.entity.BuildingIndividualEntity;
import com.css.fxfzfxqh.modules.buildingIndividual.repository.BuildingIndividualRepository;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.exceptions.BizException;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.exceptions.StrategyFactoryException;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.model.param.QueryByVersionParam;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.service.FxqhBuildingGridDataVersionService;
import com.css.fxfzfxqh.modules.buildings.calculationTasks.entity.*;
import com.css.fxfzfxqh.modules.buildings.calculationTasks.repository.CalculationTasksRepository;
import com.css.fxfzfxqh.modules.buildings.calculationTasks.service.CalculationTasksService;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.casualtiesDE.entity.PCC;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.casualtiesDE.vo.Grid13VO;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.economicLossDE.entity.EconomicLossEDCalculation;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.resistEarthquakesDE.entity.PCCName;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.resistEarthquakesDE.entity.ResistEarthquakesDE;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.resistEarthquakesDE.vo.JcLd;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.resistEarthquakesDE.vo.JcPga;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.publicOperate.repository.PublicOperateRepository;
import com.css.fxfzfxqh.modules.buildings.probabilityEvaluation.publicOperate.service.PublicOperateService;
import com.css.fxfzfxqh.modules.lifelineEngineering.entity.LifelineTaskEntity;
import com.css.fxfzfxqh.modules.seismicHazardData.entity.SettingInfluenceFliedEntity;
import com.css.fxfzfxqh.modules.seismicHazardData.repository.SeismicImpactFieldRepository;
import com.css.fxfzfxqh.modules.singleIndexRiskZoning.repository.EnterAssessQhRepository;
import com.css.fxfzfxqh.modules.singleIndexRiskZoning.vo.GdpVO;
import com.css.fxfzfxqh.modules.util.repository.PccRepository;
import com.css.fxfzfxqh.util.*;
import com.css.fxfzfxqh.web.PlatformSessionContext;
import com.css.fxfzfxqh.zcpt.sys.entity.SUser;
import com.css.fxfzfxqh.zcpt.sys.service.SUserService;
import com.css.fxfzfxqh.zcpt.sys.service.SysAreaService;
import com.css.fxfzfxqh.zcpt.sys.service.SysRoleService;
import com.css.fxfzfxqh.zcpt.sys.service.impl.SUserCacheService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slw.common.helper.PropsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: zhangSongRui
 * @CreateTime: 2023/09/20
 * @Description: 建筑物计算任务service
 */
@Slf4j
@Service
public class CalculationTasksServiceImpl implements CalculationTasksService {

    @Resource
    private CalculationTasksRepository calculationTasksRepository;
    @Resource
    SUserCacheService sUserCacheService;
    @Resource
    private SysAreaService sysAreaService;
    @Resource
    PccRepository pccRepository;
    @Resource
    BuildingIndividualRepository buildingIndividualRepository;
    @Resource
    SeismicImpactFieldRepository seismicImpactFieldRepository;
    @Resource
    private FxqhBuildingGridDataVersionService fxqhBuildingGridDataVersionService;
    @Resource
    DictItemService dictItemService;
    @Resource
    private JcsjRestManager jcsjRestManager;
    @Resource
    SysRoleService sysRoleService;
    @Resource
    PublicOperateRepository publicOperateRepository;
    @Resource
    private EnterAssessQhRepository enterAssessQhRepository;
    @Resource
    RedisTemplate redisTemplate;
    @Value("${image.ctLocalDir}")
    private String ctLocalDir;

    //任务进度
    private static Integer NUM = 0;
    //刷新一次涨多少进度
    private static Integer PROGRESS = 0;

    //判断线程是否关闭
    private static Boolean FLAG = false;
    @Resource
    private RestTemplate restTemplate;


    private static final String getGeomByProvinceCode = "datacenter/jcBoua2/getGeomByCode";
    private static final String getGeomByCityCode = "datacenter/jcBoua4/getGeomByCode";
    private static final String getGeomByCountyCode = "datacenter/jcBoua5/getGeomByCode";

//    /**
//     * 新增计算任务
//     *
//     * @param param 参数
//     */
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public String addTask(CalculationTasks param) {
//        String id = UUIDGenerator.getUUID();
//        NUM = 1;
//        //判断是否有手动输入的经纬度
//        if (PlatformObjectUtils.isNotEmpty(param.getAreaRange())) {
//            param.setCoordinateRange("POLYGON((" + param.getAreaRange() + "))");
//            //判断是否是一个面
//            boolean fang = calculationTasksRepository.verification(param.getCoordinateRange());
//            if (!fang) {
//                return "手动输入的经纬度范围不是一个面";
//            }
//        }
//        if (PlatformObjectUtils.isEmpty(param.getId())) {
//            param.setId(id);
//            param.setCreateUser(PlatformSessionContext.getUserID());
//            SUser sUser = sUserCacheService.getSUser(PlatformSessionContext.getUserID());
//            // SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
//            //创建人姓名
//            param.setCreateUserName(sUser.getUserName());
//            param.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
//            param.setDelFlag(YNEnum.N.toString());
//
//            //当前登录人所有的角色
//            StringBuilder roles = new StringBuilder();
//            List<Map> maps = JSONObject.parseArray(sysRoleService.getRoleByUserId(sUser.getUserId()), Map.class);//一个人可能有多个角色
//            for (int i = 0; i < maps.size(); i++) {
//                Map map = maps.get(i);
//                roles.append(map.get("roleCode") + ",");
//            }
//            String allRole = roles.toString();
//            String role = "3";
//            String createUserLevel = "1";
//            if (allRole.contains(FxfzConstants.QH_GJ_ROLE)) {
//                role = "0";
//            } else if (allRole.contains(FxfzConstants.QH_PROVINCE_ROLE)) {
//                //省级
//                createUserLevel = sUser.getProvinceId();
//                try {
//                    String province = sysAreaService.getAreaNameByAreaId(sUser.getProvinceId());
//                    param.setAssessProvince(province);
//                } catch (Exception e) {
//                    throw new RuntimeException("请完善当前登陆人所属省市区信息");
//                }
//                role = "1";
//            } else if (allRole.contains(FxfzConstants.PH_CITY_CODE)) {
//                //市级
//                createUserLevel = sUser.getCityId();
//                try {
//                    String area = sysAreaService.getAreaNameByAreaId(sUser.getProvinceId() + "," + sUser.getCityId());
//                    String[] strings = area.split(",");
//                    param.setAssessProvince(strings[0]);
//                    param.setAssessCity(strings[1]);
//                } catch (Exception e) {
//                    throw new RuntimeException("请完善当前登陆人所属省市区信息");
//                }
//                role = "2";
//            } else if (allRole.contains(FxfzConstants.QH_COUNTY_ROLE)) {
//                //市级
//                createUserLevel = sUser.getCountyId();
//                try {
//                    String area = sysAreaService.getAreaNameByAreaId(sUser.getProvinceId() + "," + sUser.getCityId() + "," + sUser.getCountyId());
//                    String[] strings = area.split(",");
//                    param.setAssessProvince(strings[0]);
//                    param.setAssessCity(strings[1]);
//                    param.setAssessCounty(strings[2]);
//                } catch (Exception e) {
//                    throw new RuntimeException("请完善当前登陆人所属省市区信息");
//                }
//                role = "3";
//            } else {
//                return "没有权限";
//            }
//            param.setCreateUserLevel(createUserLevel);
//            param.setRole(role);
//        } else {
//            pccRepository.delete(param.getId());
//        }
//        //默认不是当前任务
//        param.setCurrentTask("0");
//        if (param.getSeismicInputMode().contains("0")) {
//            //如果有烈度计算则设置进度为0未开始
//            if (param.getAssessObj().contains("0")) {
//                param.setStructuralLdProgress("0");
//                param.setDzbqhStructuralLdProgress("0");
//            }
//            if (param.getAssessObj().contains("1")) {
//                param.setCasualtiesLdProgress("0");
//                param.setDzbqhCasualtiesLdProgress("0");
//            }
//            if (param.getAssessObj().contains("2")) {
//                param.setLossLdProgress("0");
//                param.setDzbqhLossLdProgress("0");
//            }
//        }
//        if (param.getSeismicInputMode().contains("1")) {
//            //如果有四个概率计算则设置进度为0未开始
//            if (param.getAssessObj().contains("0")) {
//                param.setStructuralFourProgress("0");
//                param.setDzbqhStructuralFourProgress("0");
//            }
//            if (param.getAssessObj().contains("0")) {
//                param.setCasualtiesFourProgress("0");
//                param.setDzbqhCasualtiesFourProgress("0");
//            }
//            if (param.getAssessObj().contains("0")) {
//                param.setLossFourProgress("0");
//                param.setDzbqhLossFourProgress("0");
//            }
//        }
//        if (param.getSeismicInputMode().contains("2")) {
//            //如果有地震影响场计算则设置进度为0未开始
//            if (param.getAssessObj().contains("0")) {
//                param.setStructuralFieldProgress("0");
//                param.setDzbqhStructuralFieldProgress("0");
//            }
//            if (param.getAssessObj().contains("0")) {
//                param.setCasualtiesFieldProgress("0");
//                param.setDzbqhCasualtiesFieldProgress("0");
//            }
//            if (param.getAssessObj().contains("0")) {
//                param.setLossFieldProgress("0");
//                param.setDzbqhLossFieldProgress("0");
//            }
//        }
//        if (param.getSeismicInputMode().contains("3")) {
//            //如果有发生概率危险性计算则设置进度为0未开始
//            if (param.getAssessObj().contains("0")) {
//                param.setStructuralOccurrenceProgress("0");
//                param.setDzbqhStructuralOccurrenceProgress("0");
//            }
//            if (param.getAssessObj().contains("0")) {
//                param.setCasualtiesOccurrenceProgress("0");
//                param.setDzbqhCasualtiesOccurrenceProgress("0");
//            }
//            if (param.getAssessObj().contains("0")) {
//                param.setLossOccurrenceProgress("0");
//                param.setDzbqhLossOccurrenceProgress("0");
//            }
//        }
//        if (param.getSeismicInputMode().contains("4")) {
//            //如果有超越概率危险性计算则设置进度为0未开始
//            if (param.getAssessObj().contains("0")) {
//                param.setStructuralGoBeyondProgress("0");
//                param.setDzbqhStructuralGoBeyondProgress("0");
//            }
//            if (param.getAssessObj().contains("0")) {
//                param.setCasualtiesGoBeyondProgress("0");
//                param.setDzbqhCasualtiesGoBeyondProgress("0");
//            }
//            if (param.getAssessObj().contains("0")) {
//                param.setLossGoBeyondProgress("0");
//                param.setDzbqhLossGoBeyondProgress("0");
//            }
//        }
//        setCCP(param);
//        if (PlatformObjectUtils.isNotEmpty(param.getUpdateUser())) {
//            calculationTasksRepository.updateById(param);
//        } else {
//            calculationTasksRepository.addTask(param);
//        }
//        NUM = 2;
//        //重置进度条
//        calculationProgress(param);
//        log.info("开始复制数据");
//        log.info("开始复制易损性数据");
//        //根据版本和评估区域获取易损性数据
//        List<YSXMainTable> ysx = new ArrayList<>();
//        List<PCC> list = new ArrayList<>();
//        if (param.getRadio2().equals("0")) {
//            //根据省市县
//            list = param.getList();
//        } else {
//            //地图圈选
//            try {
//                List<DistrictEntity> data = jcsjRestManager.getPCCByGeomText(param.getCoordinateRange()).getData();
//                for (DistrictEntity datum : data) {
//                    PCC pcc = new PCC();
//                    pcc.setName(datum.getCounty());
//                    pcc.setCityName(datum.getCity());
//                    pcc.setPpName(datum.getProvince());
//                    if (PlatformObjectUtils.isEmpty(param.getId())) {
//                        pcc.setAssessId(id);
//                    } else {
//                        pcc.setAssessId(param.getId());
//                    }
//                    pcc.setUuid(UUIDGenerator.getUUID());
//                    list.add(pcc);
//                }
//                if (list.size() > 0) {
//                    pccRepository.batchSavePCC(list);
//                }
//            } catch (BizException e) {
//                e.printStackTrace();
//            }
//        }
//        for (PCC pcc : list) {
//            ysx.addAll(calculationTasksRepository.getfxqhJzwysx(pcc, param.getYsxVersion()));
//        }
//        for (YSXMainTable ysxMainTable : ysx) {
//            //查询对应ysx值
//            List<YSXMainTable> valueList = calculationTasksRepository.getysxValue(ysxMainTable.getId());
//            //重置主键id,防止重复
//            ysxMainTable.setId(UUIDGenerator.getUUID());
//            for (YSXMainTable mainTable : valueList) {
//                mainTable.setPid(ysxMainTable.getId());
//                calculationTasksRepository.copyYSXValue(mainTable);
//            }
//            //任务id
//            ysxMainTable.setTaskId(param.getId());
//            //复制易损性数据
//            calculationTasksRepository.copyYSXData(ysxMainTable);
//        }
//        log.info("易损性数据复制结束");
//        NUM = 5;
//        //确定评估
//        if (param.getAssessType().equals("0")) {
//            for (String inputMode : param.getSeismicInputMode().split(",")) {
//                if (inputMode.equals("1")) {
//                    //复制pga数据
//                    copyPga(param);
//                }
//                //根据不同的输入方式将对应的数据保存
//                if (param.getHouseDataFlag().equals("0")) {
//                    //单体
//                    saveDateDEMonomer(inputMode, param);
//                } else {
//                    //网格
//                    try {
//                        saveHouseData(inputMode, param);
//                    } catch (StrategyFactoryException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//        } else {
//            //概率评估
//            //根据不同的输入方式将对应的数据保存
//            if (param.getHouseDataFlag().equals("0")) {
//                //单体
//                saveDatePEMonomer(param);
//            } else {
//                //网格
//                try {
//                    saveDatePEHouseData(param);
//                } catch (StrategyFactoryException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//        log.info("复制结束");
//        NUM = 100;
//        return "新增成功";
//    }

    /**
     * 新增计算任务
     *
     * @param param 参数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addTask(CalculationTasks param) throws Exception {
        String id = UUIDGenerator.getUUID();
        NUM = 1;
        //判断是否有手动输入的经纬度
        if (PlatformObjectUtils.isNotEmpty(param.getAreaRange())) {
            param.setCoordinateRange("POLYGON((" + param.getAreaRange() + "))");
            //判断是否是一个面
            boolean fang = calculationTasksRepository.verification(param.getCoordinateRange());
            if (!fang) {
                return "手动输入的经纬度范围不是一个面";
            }
        }
        if (PlatformObjectUtils.isEmpty(param.getId())) {
            param.setId(id);
            param.setCreateUser(PlatformSessionContext.getUserID());
            SUser sUser = sUserCacheService.getSUser(PlatformSessionContext.getUserID());
            // SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
            //创建人姓名
            param.setCreateUserName(sUser.getUserName());
            param.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            param.setDelFlag(YNEnum.N.toString());

            //当前登录人所有的角色
            StringBuilder roles = new StringBuilder();
            List<Map> maps = JSONObject.parseArray(sysRoleService.getRoleByUserId(sUser.getUserId()), Map.class);//一个人可能有多个角色
            for (int i = 0; i < maps.size(); i++) {
                Map map = maps.get(i);
                roles.append(map.get("roleCode")).append(",");
            }
            String allRole = roles.toString();
            String role = "3";
            String createUserLevel = "1";
            if (allRole.contains(FxfzConstants.QH_GJ_ROLE)) {
                role = "0";
            } else if (allRole.contains(FxfzConstants.QH_PROVINCE_ROLE)) {
                //省级
                createUserLevel = sUser.getProvinceId();
                try {
                    String province = sysAreaService.getAreaNameByAreaId(sUser.getProvinceId());
                    param.setAssessProvince(province);
                } catch (Exception e) {
                    throw new RuntimeException("请完善当前登陆人所属省市区信息");
                }
                role = "1";
            } else if (allRole.contains(FxfzConstants.PH_CITY_CODE)) {
                //市级
                createUserLevel = sUser.getCityId();
                try {
                    String area = sysAreaService.getAreaNameByAreaId(sUser.getProvinceId() + "," + sUser.getCityId());
                    String[] strings = area.split(",");
                    param.setAssessProvince(strings[0]);
                    param.setAssessCity(strings[1]);
                } catch (Exception e) {
                    throw new RuntimeException("请完善当前登陆人所属省市区信息");
                }
                role = "2";
            } else if (allRole.contains(FxfzConstants.QH_COUNTY_ROLE)) {
                //市级
                createUserLevel = sUser.getCountyId();
                try {
                    String area = sysAreaService.getAreaNameByAreaId(sUser.getProvinceId() + "," + sUser.getCityId() + "," + sUser.getCountyId());
                    String[] strings = area.split(",");
                    param.setAssessProvince(strings[0]);
                    param.setAssessCity(strings[1]);
                    param.setAssessCounty(strings[2]);
                } catch (Exception e) {
                    throw new RuntimeException("请完善当前登陆人所属省市区信息");
                }
                role = "3";
            } else {
                return "没有权限";
            }
            param.setCreateUserLevel(createUserLevel);
            param.setRole(role);
        } else {
            pccRepository.delete(param.getId());
        }
        //默认不是当前任务
        param.setCurrentTask("0");
        if (param.getSeismicInputMode().contains("0")) {
            //如果有烈度计算则设置进度为0未开始
            if (param.getAssessObj().contains("0")) {
                param.setStructuralLdProgress("0");
                param.setDzbqhStructuralLdProgress("0");
            }
            if (param.getAssessObj().contains("1")) {
                param.setCasualtiesLdProgress("0");
                param.setDzbqhCasualtiesLdProgress("0");
            }
            if (param.getAssessObj().contains("2")) {
                param.setLossLdProgress("0");
                param.setDzbqhLossLdProgress("0");
            }
        }
        if (param.getSeismicInputMode().contains("1")) {
            //如果有四个概率计算则设置进度为0未开始
            if (param.getAssessObj().contains("0")) {
                param.setStructuralFourProgress("0");
                param.setDzbqhStructuralFourProgress("0");
            }
            if (param.getAssessObj().contains("0")) {
                param.setCasualtiesFourProgress("0");
                param.setDzbqhCasualtiesFourProgress("0");
            }
            if (param.getAssessObj().contains("0")) {
                param.setLossFourProgress("0");
                param.setDzbqhLossFourProgress("0");
            }
        }
        if (param.getSeismicInputMode().contains("2")) {
            //如果有地震影响场计算则设置进度为0未开始
            if (param.getAssessObj().contains("0")) {
                param.setStructuralFieldProgress("0");
                param.setDzbqhStructuralFieldProgress("0");
            }
            if (param.getAssessObj().contains("0")) {
                param.setCasualtiesFieldProgress("0");
                param.setDzbqhCasualtiesFieldProgress("0");
            }
            if (param.getAssessObj().contains("0")) {
                param.setLossFieldProgress("0");
                param.setDzbqhLossFieldProgress("0");
            }
        }
        if (param.getSeismicInputMode().contains("3")) {
            //如果有发生概率危险性计算则设置进度为0未开始
            if (param.getAssessObj().contains("0")) {
                param.setStructuralOccurrenceProgress("0");
                param.setDzbqhStructuralOccurrenceProgress("0");
            }
            if (param.getAssessObj().contains("0")) {
                param.setCasualtiesOccurrenceProgress("0");
                param.setDzbqhCasualtiesOccurrenceProgress("0");
            }
            if (param.getAssessObj().contains("0")) {
                param.setLossOccurrenceProgress("0");
                param.setDzbqhLossOccurrenceProgress("0");
            }
        }
        if (param.getSeismicInputMode().contains("4")) {
            //如果有超越概率危险性计算则设置进度为0未开始
            if (param.getAssessObj().contains("0")) {
                param.setStructuralGoBeyondProgress("0");
                param.setDzbqhStructuralGoBeyondProgress("0");
            }
            if (param.getAssessObj().contains("0")) {
                param.setCasualtiesGoBeyondProgress("0");
                param.setDzbqhCasualtiesGoBeyondProgress("0");
            }
            if (param.getAssessObj().contains("0")) {
                param.setLossGoBeyondProgress("0");
                param.setDzbqhLossGoBeyondProgress("0");
            }
        }

        String unionGeomByCode = "";
        if(("1".equals(param.getAssessType()) && "1".equals(param.getLdPga())) && "0".equals(param.getHouseDataFlag())){
        }else{
            //易损性集合
            List<YSXMainTable> ysx = new ArrayList<>();
            //概率评估如果是pga的话只做结构破坏 且没有省市区县、圈选区域等相关信息
            setCCP(param);
            List<PCC> list = new ArrayList<>();
            if (param.getRadio2().equals("0")) {
                //根据省市县
                list = param.getList();
                unionGeomByCode = publicOperateService.getUnionGeomByCode(list);
            } else {
                //地图圈选
                try {
                    List<DistrictEntity> data = jcsjRestManager.getPCCByGeomText(param.getCoordinateRange()).getData();
                    for (DistrictEntity datum : data) {
                        PCC pcc = new PCC();
                        pcc.setName(datum.getCounty());
                        pcc.setCityName(datum.getCity());
                        pcc.setPpName(datum.getProvince());
                        if (PlatformObjectUtils.isEmpty(param.getId())) {
                            pcc.setAssessId(id);
                        } else {
                            pcc.setAssessId(param.getId());
                        }
                        pcc.setUuid(UUIDGenerator.getUUID());
                        list.add(pcc);
                    }
                    if (list.size() > 0) {
                        pccRepository.batchSavePCC(list);
                    }
                    unionGeomByCode = param.getCoordinateRange();
                    param.setList(list);
                } catch (BizException e) {
                    e.printStackTrace();
                }
            }
            for (PCC pcc : list) {
                ysx.addAll(calculationTasksRepository.getfxqhJzwysx(pcc, param.getYsxVersion()));
            }
            log.info("开始复制数据");
            log.info("开始复制易损性数据");
            //根据版本和评估区域获取易损性数据
            for (YSXMainTable ysxMainTable : ysx) {
                //查询对应ysx值
                List<YSXMainTable> valueList = calculationTasksRepository.getysxValue(ysxMainTable.getId());
                //重置主键id,防止重复
                ysxMainTable.setId(UUIDGenerator.getUUID());
                for (YSXMainTable mainTable : valueList) {
                    mainTable.setPid(ysxMainTable.getId());
                    calculationTasksRepository.copyYSXValue(mainTable);
                }
                //任务id
                ysxMainTable.setTaskId(param.getId());
                //复制易损性数据
                calculationTasksRepository.copyYSXData(ysxMainTable);
            }
            log.info("易损性数据复制结束");
        }
        NUM = 2;
        //重置进度条
        calculationProgress(param);
        //更新年份
//        String year = publicOperateRepository.getYear(unionGeomByCode,param);
//        param.setYear(year);
        if (PlatformObjectUtils.isNotEmpty(param.getUpdateUser())) {
            calculationTasksRepository.updateById(param);
        } else {
            calculationTasksRepository.addTask(param);
        }

        NUM = 5;
        //确定评估
        if (param.getAssessType().equals("0")) {
            for (String inputMode : param.getSeismicInputMode().split(",")) {
                if (inputMode.equals("1")) {
                    //复制pga数据
                    copyPga(param);
                }
                //根据不同的输入方式将对应的数据保存
                if (param.getHouseDataFlag().equals("0")) {
                    //单体
                    saveDateDEMonomer(inputMode, param);
                } else {
                    //网格
                    try {
                        saveHouseData(inputMode, param);
                    } catch (StrategyFactoryException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            //概率评估
            //根据不同的输入方式将对应的数据保存
            if (param.getHouseDataFlag().equals("0")) {
                //单体  没有省市县的条件只有版本号
                saveDatePEMonomer(param);
            } else {
                //网格
                try {
                    saveDatePEHouseData(param);
                } catch (StrategyFactoryException e) {
                    e.printStackTrace();
                }
            }
        }
        log.info("复制结束");
        NUM = 100;
        return "新增成功";
    }
    //根据id查询任务
    @Override
    public CalculationTasks findById(String tasksId) {
        CalculationTasks byId = calculationTasksRepository.findById(tasksId);
        List<PCC> list = pccRepository.queryToponym(byId.getId());
        byId.setList(list);
        return byId;
    }

    @Resource
    PublicOperateService publicOperateService;

    //获取当前任务
    @Override
    public CalculationTasks getTasks() {
        String userID = PlatformSessionContext.getUserID();
        CalculationTasks byId = calculationTasksRepository.getTasks(userID);
        if (null != byId) {
            List<PCC> list = pccRepository.queryToponym(byId.getId());
            list = list.stream().distinct().collect(Collectors.toList());
            byId.setList(list);
            if (PlatformObjectUtils.isEmpty(byId.getCoordinateRange())) {
                try {
                    if(PlatformObjectUtils.isNotEmpty(list) && list.size()>0){
                        String unionGeomByCode = publicOperateService.getUnionGeomByCode(list);
                        byId.setCoordinateRange(unionGeomByCode);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            List<GdpVO> gdpByTaskId = enterAssessQhRepository.getGdpByTaskId(byId.getId());
            if(PlatformObjectUtils.isNotEmpty(gdpByTaskId) || gdpByTaskId.size()>0){
                byId.setGdpExist(1);
            }
        }

        return byId;
    }

    //设置为当前任务
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String settingTasks(String id) {
        String userID = PlatformSessionContext.getUserID();
        CalculationTasks byId = calculationTasksRepository.findById(id);
        if (!byId.getCreateUser().equals(userID)) {
            return "非本人创建数据不可修改";
        }
        calculationTasksRepository.cancelTasks(userID);
        calculationTasksRepository.settingTasks(id);
        return "设置成功";
    }

    @Override
    public Map<String, Object> getPage(int curPage, int pageSize, CalculationTasks param) {
        String userId = PlatformSessionContext.getUserID();
        SUser sUser = sUserCacheService.getSUser(PlatformSessionContext.getUserID());
        // SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        //当前登录人所有的角色
        StringBuilder roles = new StringBuilder();
        List<Map> maps = JSONObject.parseArray(role, Map.class);//一个人可能有多个角色
        for (int i = 0; i < maps.size(); i++) {
            Map map = maps.get(i);
            roles.append(map.get("roleCode") + ",");
        }
        String allRole = roles.toString();
        String createUserLevel = "1";
        //国家级
        if (allRole.contains(FxfzConstants.QH_GJ_ROLE)) {
        } else if (allRole.contains(FxfzConstants.QH_PROVINCE_ROLE)) {
            //省级
            createUserLevel = sUser.getProvinceId();
        } else if (allRole.contains(FxfzConstants.PH_CITY_CODE)) {
            //市级
            createUserLevel = sUser.getCityId();
        } else if (allRole.contains(FxfzConstants.QH_COUNTY_ROLE)) {
            //市级
            createUserLevel = sUser.getCountyId();
        } else {
            HashMap<String, Object> stringObjectHashMap = new HashMap<>();
            stringObjectHashMap.put("Message", "无权限");
            return stringObjectHashMap;
        }
        Map<String, Object> map = new HashMap();
        Map<String, Object> page = calculationTasksRepository.getPage(curPage, pageSize, param, createUserLevel);
        List<CalculationTasks> rows = (List<CalculationTasks>) page.get("rows");
        for (CalculationTasks row : rows) {
            //写入创建人名称
            row.setCreateUserName(sUser.getUserName());
        }
        map.put("rows", rows);
        map.put("total", page.get("total"));
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void upDateTasks(CalculationTasks param) throws Exception{
        NUM = 0;
        //清空复制数据
        calculationTasksRepository.deleteDataCopy(param.getId());
        //清空易损性数据
        List<YSXMainTable> ysx = calculationTasksRepository.getYSXByTaskId(param.getId());
        for (YSXMainTable ysxMainTable : ysx) {
            calculationTasksRepository.deleteYSXData(ysxMainTable);
        }
        //清空计算值
        calculationTasksRepository.deleteCalculation(param.getId());
        // //删除任务
        // calculationTasksRepository.deleteById(param.getId());
        param.setUpdateUser(PlatformSessionUtils.getUserId());
        param.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        addTask(param);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(String id) {
        calculationTasksRepository.deleteById(id);
        //清空复制数据
        calculationTasksRepository.deleteDataCopy(id);
        //清空计算值
        calculationTasksRepository.deleteCalculation(id);
        //删除图件
        File file = new File(ctLocalDir+File.separator+id);
        if(file.isDirectory() && file.exists()){
            deleteAllMapTemplate(file);
        }
        file = new File(ctLocalDir+File.separator+id+"_4");
        if(file.isDirectory() && file.exists()){
            deleteAllMapTemplate(file);
        }
    }

    public void  deleteAllMapTemplate(File file){
         deleteFile(file);
    }
    private void deleteFile(File directory){
        File[] files = directory.listFiles();
        if (PlatformObjectUtils.isNotEmpty(files)) {
            for (File file : files) {
                if(file.isFile()){
                    file.delete();
                }else{
                    deleteFile(file);
                }
            }
        }
    }


    @Override
    public Map<String, String> getRole() {
        String userId = PlatformSessionContext.getUserID();
        SUser sUser = sUserCacheService.getSUser(PlatformSessionContext.getUserID());
        // SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        //当前登录人所有的角色
        StringBuilder roles = new StringBuilder();
        List<Map> maps = JSONObject.parseArray(role, Map.class);//一个人可能有多个角色
        for (int i = 0; i < maps.size(); i++) {
            Map map = maps.get(i);
            roles.append(map.get("roleCode") + ",");
        }
        String allRole = roles.toString();
        Map<String, String> map = new HashMap<>();
        String r = null;
        //国家级
        if (allRole.contains(FxfzConstants.QH_GJ_ROLE)) {
            r = "qh_gj_role";
        } else if (allRole.contains(FxfzConstants.QH_PROVINCE_ROLE)) {
            //省级
            r = "qh_province_role";
            map.put("provinceId", sUser.getProvinceId());
        } else if (allRole.contains(FxfzConstants.PH_CITY_CODE)) {
            //市级
            r = "qh_city_role";
            map.put("provinceId", sUser.getProvinceId());
            map.put("cityId", sUser.getCityId());
        } else if (allRole.contains(FxfzConstants.QH_COUNTY_ROLE)) {
            //县级
            r = "ph_county_role";
            map.put("provinceId", sUser.getProvinceId());
            map.put("cityId", sUser.getCityId());
            map.put("countyId", sUser.getCountyId());
        } else {
            r = "无权限";
        }
        map.put("role", r);
        return map;
    }

    //复制四个概率数据
    private void copyPga(CalculationTasks param) throws Exception{
        if (null != param.getRadio2() & param.getRadio2().equals("1")) {
            try {
                if (param.getLdPga().equals("0")) {
                    List<JcLd> ldData = jcsjRestManager.getLDList1(param.getCoordinateRange(), param.getFourProbabilisticVersions()).getData();
                    if(PlatformObjectUtils.isEmpty(ldData)){
                        throw new RuntimeException("创建任务失败，无法获取四个概率水准版本为"+param.getFourProbabilisticVersions()+"的烈度数据");
                    }
                    List<JcLd> ldList = ldData.stream().filter(jcLd -> StringUtils.isBlank(jcLd.getExtends1())).collect(Collectors.toList());
                    if(PlatformObjectUtils.isEmpty(ldList)){
                        throw new RuntimeException("创建任务失败，四个概率水准版本为"+param.getFourProbabilisticVersions()+"的烈度数据存在网格id为空的情况");
                    }
                    pccRepository.saveJcLd(ldData, param.getId());
                } else {
                    List<JcPga> pgaData = jcsjRestManager.getPagList1(param.getCoordinateRange(), param.getFourProbabilisticVersions()).getData();
                    if(PlatformObjectUtils.isEmpty(pgaData)){
                        throw new RuntimeException("创建任务失败，无法获取四个概率水准版本为"+param.getFourProbabilisticVersions()+"的pga数据");
                    }
                    List<JcPga> ldList = pgaData.stream().filter(jcPga -> StringUtils.isBlank(jcPga.getExtends1())).collect(Collectors.toList());
                    if(PlatformObjectUtils.isEmpty(ldList)){
                        throw new RuntimeException("创建任务失败，四个概率水准版本为"+param.getFourProbabilisticVersions()+"的pga数据存在网格id为空的情况");
                    }
                    pccRepository.saveJcPag(pgaData, param.getId());
                }
            } catch (BizException e) {
                e.printStackTrace();
            }
        } else {
            //获得所有评估县
            List<PCC> pList = param.getList();
            for (PCC pcc : pList) {
                //将两种格式的数据,烈度格式,pga格式入库
                try {
                    if (param.getLdPga().equals("0")) {
                        List<JcLd> ldData = jcsjRestManager.getLDList(pcc.getPpName(), pcc.getCityName(), pcc.getName(), param.getFourProbabilisticVersions()).getData();
                        pccRepository.saveJcLd(ldData, param.getId());
                    } else {
                        List<JcPga> pgaData = jcsjRestManager.getPagList(pcc.getPpName(), pcc.getCityName(), pcc.getName(), param.getFourProbabilisticVersions()).getData();
                        pccRepository.saveJcPag(pgaData, param.getId());
                    }
                } catch (BizException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //返回进度条
    @Override
    public String getProgress() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (NUM >= 100) {
            NUM = 0;
            return "100";
        } else {
            return String.valueOf(NUM);
        }
    }

    //取消数据复制
    @Override
    public void cancelCopy() {

    }

    //计算进度条
    private void calculationProgress(CalculationTasks param) {
        Integer a = param.getSeismicInputMode().split(",").length;
        if (param.getRadio2().equals("0")) {
            a = a * param.getList().size();
        } else {
            a = a + 1;
        }
        if (param.getHouseDataFlag().equals("1")) {
            a = a * 13;
        }
        BigDecimal bigDecimal = BigDecimal.valueOf(95).divide(BigDecimal.valueOf(a), 0).setScale(0, BigDecimal.ROUND_HALF_UP);
        PROGRESS = Integer.valueOf(bigDecimal.toString());
    }

    //刷新进度条并判断是否取消复制
    private void refresh() {
        NUM = NUM + PROGRESS;
    }

    //根据传入条件保存概率评估单体数据
    private void saveDatePEMonomer(CalculationTasks param) {
//        List<PCC> pccList = new ArrayList<>();
//        if (param.getRadio2().equals("0")) {
//            //0为省市区县
//            //如果为根据省市县评估
//            //获得所有评估县
//            pccList = param.getList();
//        } else if (param.getRadio2().equals("1")) {
//            //1为地图圈选
//            PCC pcc = new PCC();
//            pccList.add(pcc);
//        }
        QueryByVersionParam queryByVersionParam = new QueryByVersionParam();
        String userId = PlatformSessionUtils.getUserId();
        SUser sUser = sUserCacheService.getSUser(userId);
        //当前登录人所有的角色
        StringBuilder roles = new StringBuilder();
        List<Map> maps = JSONObject.parseArray(sysRoleService.getRoleByUserId(sUser.getUserId()), Map.class);//一个人可能有多个角色
        for (int i = 0; i < maps.size(); i++) {
            Map map = maps.get(i);
            roles.append(map.get("roleCode")).append(",");
        }
        String allRole = roles.toString();
        if (allRole.contains(FxfzConstants.QH_GJ_ROLE)) {
            queryByVersionParam.setLevel("1");
            queryByVersionParam.setRole("0");
        } else if (allRole.contains(FxfzConstants.QH_PROVINCE_ROLE)) {
            //省级
            queryByVersionParam.setLevel(sUser.getProvinceId());
            queryByVersionParam.setRole("1");
        } else if (allRole.contains(FxfzConstants.PH_CITY_CODE)) {
            //市级
            queryByVersionParam.setLevel(sUser.getCityId());
            queryByVersionParam.setRole("2");
        } else if (allRole.contains(FxfzConstants.QH_COUNTY_ROLE)) {
            //市级
            queryByVersionParam.setLevel(sUser.getCountyId());
            queryByVersionParam.setRole("3");
        } else {
            return;
        }
        //写入房屋版本号
        queryByVersionParam.setVersionCode(param.getHouseData());
        //房屋单体数据
        List<BuildingIndividualEntity> all = buildingIndividualRepository.findAll1(queryByVersionParam);
        if(PlatformObjectUtils.isNotEmpty(all) && all.size()>0){
            for (BuildingIndividualEntity obj : all) {
                //写入主键id
                obj.setUuid(UUIDGenerator.getUUID());
                //写入任务id
                obj.setTaskId(param.getId());
            }
            calculationTasksRepository.saveHouseDataMonomer(all);
        }
        //写入时省市县还是地图圈选
        //queryByVersionParam.setGeomType(Integer.parseInt(param.getRadio2()));
//        for (PCC pcc : pccList) {
//            if (param.getRadio2().equals("0")) {
//                //写入省市县
//                queryByVersionParam.setProvince(pcc.getPpName());
//                queryByVersionParam.setCity(pcc.getCityName());
//                queryByVersionParam.setCounty(pcc.getName());
//                //房屋单体数据
//                List<BuildingIndividualEntity> all = buildingIndividualRepository.findAll1(queryByVersionParam);
//                for (BuildingIndividualEntity obj : all) {
//                    //写入主键id
//                    obj.setUuid(UUIDGenerator.getUUID());
//                    //写入任务id
//                    obj.setTaskId(param.getId());
//                }
//                calculationTasksRepository.saveHouseDataMonomer(all);
//            } else {
//                //写入geom
//                queryByVersionParam.setGeom(param.getCoordinateRange());
//                //房屋单体数据
//                List<BuildingIndividualEntity> all = buildingIndividualRepository.findAll1(queryByVersionParam);
//                for (BuildingIndividualEntity obj : all) {
//                    //写入主键id
//                    obj.setUuid(UUIDGenerator.getUUID());
//                    //写入任务id
//                    obj.setTaskId(param.getId());
//                }
//                calculationTasksRepository.saveHouseDataMonomer(all);
//            }
//            refresh();
//        }
    }

    private void saveDatePEHouseData(CalculationTasks param) throws StrategyFactoryException {
        String taskId = param.getId();
        List<PCC> pccList = new ArrayList<>();
        if (param.getRadio2().equals("0")) {
            //0为省市区县
            //如果为根据省市县评估
            //获得所有评估县
            pccList = param.getList();
        } else if (param.getRadio2().equals("1")) {
            //1为地图圈选
//            PCC pcc = new PCC();
//            pccList.add(pcc);
            pccList = param.getList();
        }
        //获取所以省市县
        for (PCC pcc : pccList) {
            //获取十三个结构类型字典值
            List<DictEntityVo> dictItemByDictId = dictItemService.getDictItemByDictCode("jzwglgwlx");
            for (DictEntityVo dictEntityVo : dictItemByDictId) {
                //数据视图条件
                QueryByVersionParam queryByVersionParam = new QueryByVersionParam();
                //写入版本号
                queryByVersionParam.setVersionCode(param.getHouseData());
                //写入房屋结构类型的字典值
                queryByVersionParam.setTypeCode(dictEntityVo.getDictItemCode());
                if ("1".equals(param.getRadio2())) {
                    //写入geom
                    queryByVersionParam.setGeom(param.getCoordinateRange());
                    //设置为地图圈选
                    queryByVersionParam.setGeomType(1);
                } else {
                    //写入省市县
                    queryByVersionParam.setProvince(pcc.getPpName());
                    queryByVersionParam.setCity(pcc.getCityName());
                    queryByVersionParam.setCounty(pcc.getName());
                    //默认为省市县
                    queryByVersionParam.setGeomType(0);
                }
                //获取公里网格数据
                List<Grid13VO> saveList = new ArrayList<>();
                //获取烈度的公里网格
                List<Grid13VO> gridDataList = fxqhBuildingGridDataVersionService.queryYwData(queryByVersionParam);
                for (Grid13VO grid13VO : gridDataList) {
                    //写入主键id
                    grid13VO.setUuid(UUIDGenerator.getUUID());
                    //写入任务id
                    grid13VO.setTaskId(taskId);
                    //地震输入方式 概率只会选择一个输入方式
//                    grid13VO.setSeismicInputMode(seismicInputMode);
                    //写入字典值
                    grid13VO.setDictionary(dictEntityVo.getDictItemCode());
                    if (saveList.size() > 0) {
                        List<Grid13VO> collect = saveList.stream().filter(entity1 -> entity1.getGeom().equals(grid13VO.getGeom())).collect(Collectors.toList());
                        if (PlatformObjectUtils.isNotEmpty(collect)) {
                            if (collect.get(0).getTotalArea() == null || collect.get(0).getTotalArea() == 0) {
                                saveList.remove(collect.get(0));
                                saveList.add(grid13VO);
                                continue;
                            }
                            continue;
                        }
                    }
                    saveList.add(grid13VO);
                }
                if (saveList.size() > 0) {
                    calculationTasksRepository.copyData(saveList);
                }
                refresh();
            }
        }
    }

    //根据传入条件保存确定评估单体数据
    private void saveDateDEMonomer(String inputMode, CalculationTasks param) {
        String taskId = param.getId();
        List<PCC> pccList = new ArrayList<>();
        if (param.getRadio2().equals("0")) {
            //0为省市区县
            //如果为根据省市县评估
            //获得所有评估县
            pccList = param.getList();
        } else if (param.getRadio2().equals("1")) {
            //1为地图圈选
            PCC pcc = new PCC();
//            pccList.add(pcc);
            pccList = param.getList();
        }
        String userId = PlatformSessionUtils.getUserId();
        SUser sUser = sUserCacheService.getSUser(userId);
        //当前登录人所有的角色
        StringBuilder roles = new StringBuilder();
        List<Map> maps = JSONObject.parseArray(sysRoleService.getRoleByUserId(sUser.getUserId()), Map.class);//一个人可能有多个角色
        for (int i = 0; i < maps.size(); i++) {
            Map map = maps.get(i);
            roles.append(map.get("roleCode") + ",");
        }
        String role = "";
        String level = "";
        String allRole = roles.toString();
        if (allRole.contains(FxfzConstants.QH_GJ_ROLE)) {
            level = "1";
            role = "0";
        } else if (allRole.contains(FxfzConstants.QH_PROVINCE_ROLE)) {
            //省级
            level = sUser.getProvinceId();
            role = "1";
        } else if (allRole.contains(FxfzConstants.PH_CITY_CODE)) {
            //市级
            level = sUser.getCityId();
            role = "2";
        } else if (allRole.contains(FxfzConstants.QH_COUNTY_ROLE)) {
            //市级
            level = sUser.getCountyId();
            role = "3";
        } else {
            return;
        }
        for (PCC pcc : pccList) {
            QueryByVersionParam queryByVersionParam = new QueryByVersionParam();
            queryByVersionParam.setLevel(level);
            queryByVersionParam.setRole(role);
            //写入房屋版本号
            queryByVersionParam.setVersionCode(param.getHouseData());
            if (PlatformObjectUtils.isNotEmpty(param.getRadio2()) && param.getRadio2().equals("1")) {
                //写入geom
                queryByVersionParam.setGeom(param.getCoordinateRange());
                //设置为地图圈选
                queryByVersionParam.setGeomType(1);
            } else {
                //写入省市县
                queryByVersionParam.setProvince(pcc.getPpName());
                queryByVersionParam.setCity(pcc.getCityName());
                queryByVersionParam.setCounty(pcc.getName());
                //默认为省市县
                queryByVersionParam.setGeomType(0);
            }
            if (inputMode.equals("0")) {
                //烈度 的房屋单体数据
                List<BuildingIndividualEntity> all = buildingIndividualRepository.findAll1(queryByVersionParam);
                for (BuildingIndividualEntity obj : all) {
                    //写入主键id
                    obj.setUuid(UUIDGenerator.getUUID());
                    //写入任务id
                    obj.setTaskId(taskId);
                    //地震输入方式
                    obj.setSeismicInputMode(inputMode);
                }
                calculationTasksRepository.saveHouseDataMonomer(all);
                refresh();
            } else if (inputMode.equals("1")) {
                //四个概率
                List<BuildingIndividualEntity> all = null;
                if (param.getLdPga().equals("0")) {
                    //获取在该ld数据中的所有的房屋单体数据
                    all = buildingIndividualRepository.getAllByLD(queryByVersionParam);
                    calculationTasksRepository.saveHouseDataMonomer(all);
                } else {
                    //获取在该PGA数据中的所有的房屋单体数据
                    all = buildingIndividualRepository.getAllByPGA(queryByVersionParam);
                }
                for (BuildingIndividualEntity obj : all) {
                    //写入主键id
                    obj.setUuid(UUIDGenerator.getUUID());
                    //写入任务id
                    obj.setTaskId(taskId);
                    //地震输入方式
                    obj.setSeismicInputMode(inputMode);
                }
                calculationTasksRepository.saveHouseDataMonomer(all);
                refresh();
            } else if (inputMode.equals("2")) {
                //地震影响场
                //根据地震影响场版号查询影响场id
                List<SettingInfluenceFliedEntity> seismicInfluence = seismicImpactFieldRepository.getInfluencefliedById(param.getInfluenceFieldVersion());
                for (SettingInfluenceFliedEntity settingInfluenceFliedEntity : seismicInfluence) {
                    //写入地震影响场id
                    queryByVersionParam.setField(settingInfluenceFliedEntity.getId());
                    List<BuildingIndividualEntity> all = buildingIndividualRepository.queryALLByInfluence(queryByVersionParam);
                    //这里将查询出来的值转换为字典值
                    String dzIntensity = convertDzIntensity(settingInfluenceFliedEntity.getDzIntensity());
                    refresh();
                    refresh();
                    refresh();
                    for (BuildingIndividualEntity obj : all) {
                        //写入主键id
                        obj.setUuid(UUIDGenerator.getUUID());
                        //写入任务id
                        obj.setTaskId(taskId);
                        //地震输入方式
                        obj.setSeismicInputMode(inputMode);
                        obj.setDzIntensity(dzIntensity);
                        obj.setDzId(settingInfluenceFliedEntity.getId());
                    }
                    calculationTasksRepository.saveHouseDataMonomer(all);
                }
                refresh();
            }
        }
    }

    /**
     * 保存房屋网格数据
     *
     * @param param
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveHouseData(String seismicInputMode, CalculationTasks param) throws StrategyFactoryException {
        String taskId = param.getId();
        List<PCC> pccList = new ArrayList<>();
        if (param.getRadio2().equals("0")) {
            //0为省市区县
            //如果为根据省市县评估
            //获得所有评估县
            pccList = param.getList();
        } else if (param.getRadio2().equals("1")) {
            //1为地图圈选
            pccList = param.getList();
        }
        //获取所以省市县
        for (PCC pcc : pccList) {
            //获取十三个结构类型字典值
            List<DictEntityVo> dictItemByDictId = dictItemService.getDictItemByDictCode("jzwglgwlx");
            for (DictEntityVo dictEntityVo : dictItemByDictId) {
                //数据视图条件
                QueryByVersionParam queryByVersionParam = new QueryByVersionParam();
                //写入版本号
                queryByVersionParam.setVersionCode(param.getHouseData());
                //写入房屋结构类型的字典值
                queryByVersionParam.setTypeCode(dictEntityVo.getDictItemCode());
                if (null != param.getRadio2() & param.getRadio2().equals("1")) {
                    //写入geom
                    queryByVersionParam.setGeom(param.getCoordinateRange());
                    //设置为地图圈选
                    queryByVersionParam.setGeomType(1);
                } else {
                    //写入省市县
                    queryByVersionParam.setProvince(pcc.getPpName());
                    queryByVersionParam.setCity(pcc.getCityName());
                    queryByVersionParam.setCounty(pcc.getName());
                    //默认为省市县
                    queryByVersionParam.setGeomType(0);
                }
                List<Grid13VO> saveList = new ArrayList<>();
                //获取公里网格数据
                List<Grid13VO> gridDataList = null;
                if (seismicInputMode.equals("0")) {
                    //烈度的公里网格
                    gridDataList = fxqhBuildingGridDataVersionService.queryYwData(queryByVersionParam);
                    for (Grid13VO grid13VO : gridDataList) {
                        //写入主键id
                        grid13VO.setUuid(UUIDGenerator.getUUID());
                        //写入任务id
                        grid13VO.setTaskId(taskId);
                        //地震输入方式
                        grid13VO.setSeismicInputMode(seismicInputMode);
                        //写入字典值
                        grid13VO.setDictionary(dictEntityVo.getDictItemCode());
                        if(StringUtils.isNotBlank(grid13VO.getExtends1())){
                            if (saveList.size() > 0) {
                                List<Grid13VO> collect = saveList.stream().filter(entity1 -> entity1.getExtends1().equals(grid13VO.getExtends1())).collect(Collectors.toList());
                                if (PlatformObjectUtils.isNotEmpty(collect)) {
                                    if (collect.get(0).getTotalArea() == null || collect.get(0).getTotalArea() == 0) {
                                        saveList.remove(collect.get(0));
                                        saveList.add(grid13VO);
                                        continue;
                                    }
                                    continue;
                                }
                            }
                            saveList.add(grid13VO);
                        }
                    }
                    if (saveList.size() > 0) {
                        calculationTasksRepository.copyData(saveList);
                    }
                } else if (seismicInputMode.equals("2")) {
                    //地震影响场
                    List<SettingInfluenceFliedEntity> seismicInfluence = seismicImpactFieldRepository.getInfluencefliedById(param.getInfluenceFieldVersion());
                    for (SettingInfluenceFliedEntity settingInfluenceFliedEntity : seismicInfluence) {
                        //写入地震影响场
                        queryByVersionParam.setField(settingInfluenceFliedEntity.getId());
                        //地震影响场的公里网格
                        gridDataList = fxqhBuildingGridDataVersionService.queryDataByParam(queryByVersionParam);
                        //这里将查询出来的值转换为字典值
                        String dzIntensity = convertDzIntensity(settingInfluenceFliedEntity.getDzIntensity());
                        for (Grid13VO grid13VO : gridDataList) {
                            //写入主键id
                            grid13VO.setUuid(UUIDGenerator.getUUID());
                            //写入任务id
                            grid13VO.setTaskId(taskId);
                            //地震影响场烈度
                            grid13VO.setDzIntensity(dzIntensity);
                            grid13VO.setDzId(settingInfluenceFliedEntity.getId());
                            //地震输入方式
                            grid13VO.setSeismicInputMode(seismicInputMode);
                            //写入字典值
                            grid13VO.setDictionary(dictEntityVo.getDictItemCode());
                            if(StringUtils.isNotBlank(grid13VO.getExtends1())){
                                if (PlatformObjectUtils.isNotEmpty(saveList)) {
                                    List<Grid13VO> collect = saveList.stream().filter(entity1 -> entity1.getExtends1().equals(grid13VO.getExtends1())).collect(Collectors.toList());
                                    if (PlatformObjectUtils.isNotEmpty(collect)) {
                                        if (collect.get(0).getTotalArea() == null || collect.get(0).getTotalArea() == 0) {
                                            saveList.remove(collect.get(0));
                                            saveList.add(grid13VO);
                                            continue;
                                        }
                                        continue;
                                    }
                                }
                                saveList.add(grid13VO);
                            }
                        }
                    }
                    if (saveList.size() > 0) {
                        saveList = saveList.stream().distinct().collect(Collectors.toList());
                        calculationTasksRepository.copyData(saveList);
                    }
                } else if (seismicInputMode.equals("1")) {
                    //写入评估记录id
                    queryByVersionParam.setAssessId(taskId);
                    queryByVersionParam.setFourProbabilisticVersions(param.getFourProbabilisticVersions());
                    //四个概率水准
                    //用概率水准与公里格网相交
                    if (param.getLdPga().equals("0")) {
                        gridDataList = fxqhBuildingGridDataVersionService.getJcld(queryByVersionParam);
                    } else {
                        gridDataList = fxqhBuildingGridDataVersionService.getPga(queryByVersionParam);
                    }
                    for (Grid13VO grid13VO : gridDataList) {
                        //写入主键id
                        grid13VO.setUuid(UUIDGenerator.getUUID());
                        //写入任务id
                        grid13VO.setTaskId(taskId);
                        //地震输入方式
                        grid13VO.setSeismicInputMode(seismicInputMode);
                        //写入字典值
                        grid13VO.setDictionary(dictEntityVo.getDictItemCode());
                        if(StringUtils.isNotBlank(grid13VO.getExtends1())){
                            if (PlatformObjectUtils.isNotEmpty(saveList)) {
                                List<Grid13VO> collect = saveList.stream().filter(entity1 -> entity1.getExtends1().equals(grid13VO.getExtends1())).collect(Collectors.toList());
                                if (PlatformObjectUtils.isNotEmpty(collect)) {
                                    if (collect.get(0).getTotalArea() == null || collect.get(0).getTotalArea() == 0) {
                                        saveList.remove(collect.get(0));
                                        saveList.add(grid13VO);
                                        continue;
                                    }
                                    continue;
                                }
                            }
                            saveList.add(grid13VO);
                        }
                    }
                    if (saveList.size() > 0) {
                        calculationTasksRepository.copyData(saveList);
                    }
                }
                refresh();
            }
        }
    }

    //根据pag值转换成烈度
    private String sectionPag(Double value) {
        if (0.04 <= value & value < 0.09) {
            return "ld1";
        }
        if (0.09 <= value & value < 0.19) {
            return "ld2";
        }
        if (0.19 <= value & value < 0.38) {
            return "ld3";
        }
        if (0.38 <= value & value < 0.75) {
            return "ld4";
        }
        if (0.75 <= value) {
            return "ld5";
        }
        return null;
    }

    private String sectionLD(String value) {
        if ("6".equals(value)) {
            return "ld1";
        }
        if ("7".equals(value)) {
            return "ld2";
        }
        if ("8".equals(value)) {
            return "ld3";
        }
        if ("9".equals(value)) {
            return "ld4";
        }
        if ("10".equals(value)) {
            return "ld5";
        }
        return null;
    }

    /**
     * 将影响场烈度转化为字典值
     *
     * @param dzIntensity 地震影响场的地震影响场地震烈度
     * @return 对应字典值
     */
    private String convertDzIntensity(String dzIntensity) {
        if (dzIntensity.equals("6")) {
            return "ld1";
        }
        if (dzIntensity.equals("7")) {
            return "ld2";
        }
        if (dzIntensity.equals("8")) {
            return "ld3";
        }
        if (dzIntensity.equals("9")) {
            return "ld4";
        }
        if (dzIntensity.equals("10")) {
            return "ld5";
        }
        return null;
    }

    //写入省市县
    private List<PCC> getCCP(List<PCC> pccList) {
        List<PCC> pccList1 = new ArrayList<>();
        if (pccList.size() != 0) {
            for (PCC pcc : pccList) {
                if (PlatformObjectUtils.isNotEmpty(pcc.getPpName())) {
                    if (PlatformObjectUtils.isEmpty(pcc.getCityName())) {
                        String childArea1 = sysAreaService.getChildAreaById(pcc.getPid());
                        List<PCCName> objects1 = JSON.parseArray(childArea1, PCCName.class);
                        for (PCCName pccName1 : objects1) {
                            String childArea2 = sysAreaService.getChildAreaById(pccName1.getId());
                            List<PCCName> objects2 = JSON.parseArray(childArea2, PCCName.class);
                            for (PCCName pccName2 : objects2) {
                                PCC pcc1 = new PCC();
                                pcc1.setUuid(UUIDGenerator.getUUID());
                                pcc1.setPid(pcc.getPid());
                                pcc1.setPpName(pcc.getPpName());
                                pcc1.setCid(pccName1.getId());
                                pcc1.setCityName(pccName1.getName());
                                pcc1.setName(pccName2.getName());
                                pcc1.setId(pccName2.getId());
                                pccList1.add(pcc1);
                            }
                        }
                    } else {
                        if (PlatformObjectUtils.isEmpty(pcc.getName())) {
                            String childArea = sysAreaService.getChildAreaById(pcc.getCid());
                            List<PCCName> objects = JSON.parseArray(childArea, PCCName.class);
                            for (PCCName pccName : objects) {
                                PCC pcc1 = new PCC();
                                pcc1.setUuid(UUIDGenerator.getUUID());
                                pcc1.setPid(pcc.getPid());
                                pcc1.setPpName(pcc.getPpName());
                                pcc1.setCid(pcc.getCid());
                                pcc1.setCityName(pcc.getCityName());
                                pcc1.setName(pccName.getName());
                                pcc1.setId(pccName.getId());
                                pccList1.add(pcc1);
                            }
                        } else {
                            pcc.setUuid(UUIDGenerator.getUUID());
                            pccList1.add(pcc);
                        }
                    }
                } else {
                    pcc.setUuid(UUIDGenerator.getUUID());
                    pccList1.add(pcc);
                }
            }

        }
        return pccList1;
    }
    //写入省市县
    @Transactional(rollbackFor = Exception.class)
    void setCCP(CalculationTasks param) {
        List<PCC> pccList1 = new ArrayList<>();
        List<PCC> pccList = param.getList();
        if (pccList.size() != 0) {
            for (PCC pcc : pccList) {
                if (PlatformObjectUtils.isNotEmpty(pcc.getPpName())) {
                    if (PlatformObjectUtils.isEmpty(pcc.getCityName())) {
                        String childArea1 = sysAreaService.getChildAreaById(pcc.getPid());
                        List<PCCName> objects1 = JSON.parseArray(childArea1, PCCName.class);
                        for (PCCName pccName1 : objects1) {
                            String childArea2 = sysAreaService.getChildAreaById(pccName1.getId());
                            List<PCCName> objects2 = JSON.parseArray(childArea2, PCCName.class);
                            for (PCCName pccName2 : objects2) {
                                String geom = getGeomById(pcc.getPid(),pccName1.getId(),pccName2.getId());
                                PCC pcc1 = new PCC();
                                pcc1.setAssessId(param.getId());
                                pcc1.setUuid(UUIDGenerator.getUUID());
                                pcc1.setPid(pcc.getPid());
                                pcc1.setPpName(pcc.getPpName());
                                pcc1.setCid(pccName1.getId());
                                pcc1.setCityName(pccName1.getName());
                                pcc1.setName(pccName2.getName());
                                pcc1.setId(pccName2.getId());
                                pcc1.setGeom(geom);
                                pccList1.add(pcc1);
                            }
                        }
                    } else {
                        if (PlatformObjectUtils.isEmpty(pcc.getName())) {
                            String childArea = sysAreaService.getChildAreaById(pcc.getCid());
                            List<PCCName> objects = JSON.parseArray(childArea, PCCName.class);
                            for (PCCName pccName : objects) {
                                PCC pcc1 = new PCC();
                                pcc1.setAssessId(param.getId());
                                pcc1.setUuid(UUIDGenerator.getUUID());
                                pcc1.setPid(pcc.getPid());
                                pcc1.setPpName(pcc.getPpName());
                                pcc1.setCid(pcc.getCid());
                                pcc1.setCityName(pcc.getCityName());
                                pcc1.setName(pccName.getName());
                                pcc1.setId(pccName.getId());
                                pcc1.setGeom(getGeomById(pcc.getPid(),pcc.getId(),pcc.getId()));
                                pccList1.add(pcc1);
                            }
                        } else {
                            pcc.setAssessId(param.getId());
                            pcc.setUuid(UUIDGenerator.getUUID());
                            pcc.setGeom(getGeomById(pcc.getPid(),pcc.getId(),pcc.getId()));
                            pccList1.add(pcc);
                        }
                    }
                } else {
                    pcc.setAssessId(param.getId());
                    pcc.setUuid(UUIDGenerator.getUUID());
                    pccList1.add(pcc);
                }
            }
            pccRepository.batchSavePCC(pccList1);
        }
    }

    private String getGeomById( String province,String city,String county){
        Map<String, String> areaIdCodeMap = (Map<String, String>) JSON.parse((String) redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "areaIdCodeMap"));
        try {
            String type="3";
            String code=null;
            if (PlatformObjectUtils.isNotEmpty(province)){
                if (PlatformObjectUtils.isEmpty(city)){
                    type="1";
                    if (areaIdCodeMap==null||areaIdCodeMap.size()<1) {
                        code = sysAreaService.getDivisionCodeById(province);
                    }else {
                        code = areaIdCodeMap.get(province);
                    }
                }else {
                    if (PlatformObjectUtils.isEmpty(county)){
                        type="2";
                        if (areaIdCodeMap==null||areaIdCodeMap.size()<1) {
                            code = sysAreaService.getDivisionCodeById(city);
                        }else {
                            code = areaIdCodeMap.get(city);
                        }
                    }else {
                        if (areaIdCodeMap==null||areaIdCodeMap.size()<1) {
                            code = sysAreaService.getDivisionCodeById(county);
                        }else {
                            code = areaIdCodeMap.get(county);
                        }
                    }
                }
            }else {
                return null;
            }
            HttpEntity<String> entity = new HttpEntity<>(code, buildBaseHeaders());
            String url = null;
            try {
                if ("1".equals(type)) {
                    url = getBaseUrl(getGeomByProvinceCode);
                } else if ("2".equals(type)) {
                    url = getBaseUrl(getGeomByCityCode);
                } else {
                    url = getBaseUrl(getGeomByCountyCode);
                }
            } catch (BizException e) {
                return null;
            }
            JSONObject body = restTemplate.exchange(url, HttpMethod.POST, entity, JSONObject.class).getBody();
            if (body == null) {
                return null;
            }
            return (String) body.get("data");
        } catch (RestClientException e) {
            throw e;
        }
    }

    /**
     * 获取基础请求路径
     *
     * @return
     */
    private static String getBaseUrl(String apiUrl) throws BizException {
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String jcsjRestUrl = configGroup.getProperty("jcsjRestUrl");
        if (StringUtils.isBlank(jcsjRestUrl)) {
            throw new BizException("配置文件未发现基础数据系统接口URL");
        }
        if (!StringUtils.endsWith(jcsjRestUrl, "/")) {
            jcsjRestUrl += "/";
        }
        return jcsjRestUrl + apiUrl;
    }

    private static HttpHeaders buildBaseHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "dzzhfxpgyqhxt");
        headers.setContentType(MediaType.APPLICATION_JSON);
        return headers;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveFxqhBuildingPriceTask(FxqhBuildingPriceTaskEntity entity) {
        calculationTasksRepository.saveFxqhBuildingPriceTask(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveFxqhHosPeoTask(FxqhHosPeoTaskEntity entity) {
        calculationTasksRepository.saveFxqhHosPeoTask(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delFxqhBuildingPriceTask(String taskId) {
        calculationTasksRepository.delFxqhBuildingPriceTask(taskId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delFxqhHosPeoTask(String taskId) {
        calculationTasksRepository.delFxqhHosPeoTask(taskId);
    }

    @Override
    public List<FxqhBuildingPriceTaskEntity> getList1ByTaskId(String taskId) {
        return calculationTasksRepository.getList1ByTaskId(taskId);
    }

    @Override
    public List<FxqhHosPeoTaskEntity> getList2ByTaskId(String taskId) {
        return calculationTasksRepository.getList2ByTaskId(taskId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateById(CalculationTasks entity) {
        calculationTasksRepository.updateById(entity);
    }

    @Override
    public String getYear(CalculationTasks param) throws Exception {
        //当前登录人所有的角色
        String userId = PlatformObjectUtils.isNotEmpty(PlatformSessionContext.getUserID())?PlatformSessionContext.getUserID():"80cd530287e54c6788925adf2dfc9da1";
        SUser sUser = sUserCacheService.getSUser(userId);
        StringBuilder roles = new StringBuilder();
        List<Map> maps = JSONObject.parseArray(sysRoleService.getRoleByUserId(sUser.getUserId()), Map.class);//一个人可能有多个角色
        for (int i = 0; i < maps.size(); i++) {
            Map map = maps.get(i);
            roles.append(map.get("roleCode")).append(",");
        }
        String allRole = roles.toString();
        String role = "3";
        if (allRole.contains(FxfzConstants.QH_GJ_ROLE)) {
            role = "0";
        } else if (allRole.contains(FxfzConstants.QH_PROVINCE_ROLE)) {
            role = "1";
        } else if (allRole.contains(FxfzConstants.PH_CITY_CODE)) {
            //市级
            role = "2";
        } else if (allRole.contains(FxfzConstants.QH_COUNTY_ROLE)) {
            //区县
            role = "3";
        } else {
            return "没有权限";
        }
        param.setRole(role);
        String unionGeomByCode = "";
        List<PCC> list = new ArrayList<>();
        if (param.getRadio2().equals("0")) {
            //根据省市县
            list = param.getList();
            list = getCCP(list);
            unionGeomByCode = publicOperateService.getUnionGeomByCode(list);
        } else {
            //地图圈选
            unionGeomByCode = param.getCoordinateRange();
        }
        return publicOperateRepository.getYear(unionGeomByCode,param);
    }
}
